package io.geekidea.boot.supplier.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.geekidea.boot.Import.ExcelListener;
//import io.geekidea.boot.area.entity.ExcelArea;
//import io.geekidea.boot.area.mapper.ExcelAreaMapper;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiCode;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.supplier.dto.SupplierAddDto;
import io.geekidea.boot.supplier.dto.SupplierBanDto;
import io.geekidea.boot.supplier.dto.SupplierDto;
//import io.geekidea.boot.supplier.entity.ExcelSupplier;
import io.geekidea.boot.supplier.entity.ExcelSupplier;
import io.geekidea.boot.supplier.entity.Supplier;
//import io.geekidea.boot.supplier.mapper.ExcelSupplierMapper;
import io.geekidea.boot.supplier.mapper.ExcelSupplierMapper;
import io.geekidea.boot.supplier.service.SupplierService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/supplier")
@Tag(name = "供应商管理")
public class SupplierController {


    @Resource
    private SupplierService supplierService;

    @Autowired
    private ExcelSupplierMapper excelSupplierMapper;

    @PostMapping("/import")
    public ApiResult myImport(@RequestPart MultipartFile file) {
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            if (filename==null||filename==""){
                return ApiResult.error("file不存在");
            }
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, ExcelSupplier.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 1) {
                for (int i = 0; i < list.size(); i++) {
                    ExcelSupplier excel = (ExcelSupplier) list.get(i);
                    //使用mybatis-plus添加到数据库
                    if (((ExcelSupplier) list.get(i)).getName() == "" || ((ExcelSupplier) list.get(i)).getName() == null) {
                        return ApiResult.error("请输入供应商名称");
                    } else if (((ExcelSupplier) list.get(i)).getCode()== ""||((ExcelSupplier) list.get(i)).getCode()==null){
                        return ApiResult.error("请输入供应商编码");
                    } else if (((ExcelSupplier) list.get(i)).getType()== ""||((ExcelSupplier) list.get(i)).getType()==null){
                        return ApiResult.error("请输入供应商类型");
                    }else {
                        excelSupplierMapper.insert(excel);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("导入失败，请检查是否有相同战区或文件格式");
        }

        return ApiResult.success("导入成功",200);
    }


    @PostMapping("/list")
    @Operation(summary = "查询供应商所有数据")
    public ApiResult supplierList(){
      List<Supplier> supplierList = supplierService.list();
       return ApiResult.success(supplierList);
    }

    //逻辑删除
    @GetMapping("/del/{id}")
    @Operation(summary = "逻辑删除",description = "根据id逻辑删除对应供应商")
    public ApiResult del(@PathVariable Integer id){
        boolean update = supplierService.delById(id);
        if (!update) {
            return ApiResult.success("删除失败");
        }
        return ApiResult.success("删除成功",200);

    }



    @PostMapping("/update")
    public ApiResult updateStore(@RequestBody SupplierAddDto supplierAddDto){
        Supplier supplier=new Supplier();
        BeanUtil.copyProperties(supplierAddDto,supplier);
        supplierService.updateById(supplier);
        return ApiResult.success("修改供应商信息成功",200);
    }


    @GetMapping("/one/{id}")
    @Operation(method = "Get",tags = "根据id查询供应商")
    public ApiResult queryOne(@PathVariable Integer id) {
        Supplier supplier = supplierService.getById(id);
        return ApiResult.result(ApiCode.SUCCESS,supplier);
    }

    @PostMapping("/add")
    @Operation(summary = "添加一个供应商")
    public ApiResult addSupplier(@RequestBody SupplierAddDto supplierDto) {
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierDto, supplier);
        boolean result = supplierService.save(supplier);
        return result?ApiResult.success("新增成功",200):ApiResult.fail("插入失败");
    }

//    @PostMapping("/query/all")
//    @Operation(method = "Post",tags = "查询所有供应商")
//    public ApiResult queryByCondition(@RequestBody SupplierDto supplierDto) {
//        IPage<Supplier> page=new Page<>(supplierDto.getPage(),supplierDto.getSize());
//        page = supplierService.page(page);
//        Page<Supplier> supplierPages=new Page<>();
//        supplierPages.setList(page.getRecords());
//        supplierPages.setTotal(page.getTotal());
//        supplierPages.setSize(supplierDto.getSize());
//        return ApiResult.success(supplierPages);
//    }

    @PostMapping("/query/page")
    @Operation(method = "Post",tags = "根据供应商类型,编码,名称条件查询")
    public ApiResult queryAll(@RequestBody SupplierDto supplierDto) {
//        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like(StringUtils.isNotBlank(supplierDto.getType()),"type",supplierDto.getType());
//        queryWrapper.like(StringUtils.isNotBlank(supplierDto.getName()), "name", supplierDto.getName());
//        queryWrapper.eq(StringUtils.isNotBlank(supplierDto.getCode()), "code", supplierDto.getCode());
//        IPage<Supplier> page=new Page<>(supplierDto.getPage(),supplierDto.getSize());
//        page = supplierService.page(page,queryWrapper);
//        Page<Supplier> supplierPages=new Page<>();
//        supplierPages.setList(page.getRecords());
//        supplierPages.setTotal(page.getTotal());
//        supplierPages.setSize(page.getSize());
//        return ApiResult.success(supplierPages);
        Page<Supplier> page=new Page<>(supplierDto.getPage(),supplierDto.getSize());
        LambdaQueryWrapper<Supplier> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(supplierDto.getType()),Supplier::getType,supplierDto.getType());
        lambdaQueryWrapper.like(StringUtils.isNotBlank(supplierDto.getName()), Supplier::getName, supplierDto.getName());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(supplierDto.getCode()), Supplier::getCode, supplierDto.getCode());
        Page<Supplier> pageDto=supplierService.page(page,lambdaQueryWrapper);
        PageDto<Supplier> pageInfo=new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);

    }

    @GetMapping("/name")
    @Operation(method = "Get",tags = "所有供应商的名称")
    public ApiResult getAllSuppliers(){
        List<Supplier> list=supplierService.list();

        return ApiResult.result(ApiCode.SUCCESS,list);
    }

    @PostMapping("/ban/")
    @Operation(method = "Post",tags = "禁用/启用供应商")
    public ApiResult banSupplier(@RequestBody SupplierBanDto supplierBanDto){
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierBanDto,supplier);
        boolean update = supplierService.updateById(supplier);
        return update?ApiResult.result(ApiCode.SUCCESS):ApiResult.fail("禁用失败");
    }

    @DeleteMapping("/delete/{id}")
    @Operation(method = "Delete",tags = "(逻辑)删除供应商")
    public ApiResult deleteSupplier(@PathVariable Integer id){
        boolean result = supplierService.removeById(id);
        return result?ApiResult.result(ApiCode.SUCCESS):ApiResult.fail("删除失败");
    }
}
